package hongcaosp.app.android.user.dynamic;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tencent.liteav.demo.play.SuperPlayerModel;

import hongcaosp.app.android.R;
import hongcaosp.app.android.common.BaseHolder;
import hongcaosp.app.android.modle.bean.IDynamic;
import hongcaosp.app.android.modle.bean.IUser;
import hongcaosp.app.android.video.PlayConstant;
import hongcaosp.app.android.video.VisiblePage;
import hongcaosp.app.android.video.player.PlayCountListener;
import hongcaosp.app.android.video.player.PlayVideoManager;
import hongcaosp.app.android.video.player.PlayerView;
import hongcaosp.app.android.video.player.VideoProxy;
import xlj.lib.android.base.utils.DensityUtils;
import xlj.lib.android.base.utils.GlideUtils;
import xlj.lib.android.base.view.RatioFrameLayout;
import xlj.lib.android.base.view.RoundViewOutlineProvider;

public class DynamicHolder extends BaseHolder<IDynamic> implements VideoProxy {
    private Context context;
    private ImageView userLogoIV;
    private TextView usernameTV,timeTV,desTV,likecountTV,commentcountTV,shareTV;
    public PlayerView playerView;
    private RatioFrameLayout ratioRF;
    private ImageView playBtn,coverIV;
    private ContentLoadingProgressBar loadingIV;
    private static PlayCountListener playCountListener;
    private VideoClickListener videoClickListener;

    private IDynamic dynamic;
    private int state;
    private boolean isStart;

    private boolean isPlaying;

    private VisiblePage obj;

    public static void setPlayCountListener(PlayCountListener playCountListener) {
        DynamicHolder.playCountListener = playCountListener;
    }

    public DynamicHolder(final Context context, View itemView, final VisiblePage obj) {
        super(itemView);
        this.context = context;
        userLogoIV = itemView.findViewById(R.id.user_logo);
        usernameTV = itemView.findViewById(R.id.user_name);
        timeTV = itemView.findViewById(R.id.update_time);
        desTV = itemView.findViewById(R.id.descrip);
        playerView = itemView.findViewById(R.id.player);
        likecountTV = itemView.findViewById(R.id.like_count);
        commentcountTV = itemView.findViewById(R.id.comment_count);
        ratioRF = itemView.findViewById(R.id.ratio_fm);
        shareTV = itemView.findViewById(R.id.share);
        playBtn = itemView.findViewById(R.id.play_btn);
        coverIV = itemView.findViewById(R.id.video_cover);
        loadingIV = itemView.findViewById(R.id.loading_iv);
        loadingIV.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(context,R.color.white), PorterDuff.Mode.MULTIPLY);
        this.obj = obj;
        playerView.setIsLoop(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ratioRF.setOutlineProvider(new RoundViewOutlineProvider(DensityUtils.dip2px(context,5)));
            ratioRF.setClipToOutline(true);
        }
        playerView.setPlayerStateListener(new PlayerView.PlayerStateListener() {
            @Override
            public void onPrepare() {
                state = 2;
            }

            @Override
            public void onStart() {
                state = 1;
                isPlaying = true;
                playBtn.setImageResource(R.drawable.icon_small_state_play);
                loadingIV.setVisibility(View.GONE);
                playBtn.setVisibility(View.VISIBLE);
                PlayVideoManager.getInstance().onPlay(DynamicHolder.this,obj);
//                if (!isStart || (obj != null && !obj.isVisible())) {
//                    pauseVideo();
//                }
            }

            @Override
            public void onPause() {
                state = 2;
                isPlaying = false;
                playBtn.setImageResource(R.drawable.icon_small_state_pause);
            }

            @Override
            public void onStop() {
                state = 3;
                isPlaying = false;
                coverIV.setVisibility(View.VISIBLE);
                playBtn.setImageResource(R.drawable.icon_small_state_pause);
            }

            @Override
            public void onPlayProgress(int progress, int duration) {
                loadingIV.setVisibility(View.GONE);
                playBtn.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFirstFrame() {
                if (!PlayConstant.isPlayOk) {
                    pauseVideo();
                }
                loadingIV.setVisibility(View.GONE);
                coverIV.setVisibility(View.GONE);
                state = 9;
            }

            @Override
            public void onLoading() {
                state = 10;
                loadingIV.setVisibility(View.VISIBLE);
                playBtn.setVisibility(View.GONE);
            }

            @Override
            public void onLoadEnd() {
                state = 11;
                loadingIV.setVisibility(View.GONE);
                playBtn.setVisibility(View.VISIBLE);
//                if (obj != null && !obj.isVisible()) {
//                    pauseVideo();
//                }
            }

            @Override
            public void onFailed(String message) {
                loadingIV.setVisibility(View.GONE);
                playBtn.setVisibility(View.VISIBLE);
            }
        });

        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlaying) {
                    pauseVideo();
                } else {
                    if (state == 2) {
                        resumeVideo();
                    } else {
                        playVideo();
                    }
                }
            }
        });

        likecountTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dynamic != null && videoClickListener != null) {
                    if (!dynamic.isLiked()) {
                        videoClickListener.onLike(dynamic, DynamicHolder.this);
                    } else {
                        videoClickListener.unLike(dynamic, DynamicHolder.this);
                    }
                }
            }
        });

        shareTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoClickListener != null) {
                    videoClickListener.onShare(dynamic);
                }
            }
        });

        commentcountTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dynamic != null && videoClickListener != null) {
                    videoClickListener.onComment(dynamic,DynamicHolder.this);
                }
            }
        });

        userLogoIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dynamic != null && videoClickListener != null) {
                    videoClickListener.onUserClick(dynamic.getAuthor());
                }
            }
        });
    }

    public void setVideoClickListener(VideoClickListener videoClickListener) {
        this.videoClickListener = videoClickListener;
    }

    @Override
    public void setData(final IDynamic iDynamic) {
        this.dynamic = iDynamic;
        GlideUtils.loadCircleImage(context,iDynamic.getAuthor().getUserLogo(),userLogoIV,R.drawable.icon_head);
        coverIV.setVisibility(View.VISIBLE);

        usernameTV.setText(iDynamic.getAuthor().getUserName());
        timeTV.setText(iDynamic.getUpdateTime());

        freshComment();
        freshLike();
        freshForwords();

        if (TextUtils.isEmpty(iDynamic.getDescription())) {
            desTV.setVisibility(View.GONE);
        } else {
            desTV.setVisibility(View.VISIBLE);
            desTV.setText(iDynamic.getDescription());
        }
        if (dynamic.getVideoRatio() < 1) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ratioRF.getLayoutParams();
            lp.rightMargin = 0;
            ratioRF.setLayoutParams(lp);
            ratioRF.setHeightRatio(dynamic.getVideoRatio());
        } else {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) ratioRF.getLayoutParams();
            lp.rightMargin = DensityUtils.dip2px(context,45);
            ratioRF.setLayoutParams(lp);
            if (dynamic.getVideoRatio() > 1.5) {
                ratioRF.setHeightRatio(1.5f);
            } else {
                ratioRF.setHeightRatio(dynamic.getVideoRatio());
            }
        }

        playerView.post(new Runnable() {
            @Override
            public void run() {
                Glide.with(context).load(iDynamic.getVideoImage()).diskCacheStrategy(DiskCacheStrategy.SOURCE).centerCrop().into(coverIV);
                if (obj == null || obj.isVisible()) {
                    if (!isVideoCover()) {
                        prepare(true);
                    }
                }
            }
        });

    }

    public boolean isVideoCover() {
        if (playBtn != null) {
            boolean cover = false;
            Rect rect = new Rect();
            cover = playBtn.getGlobalVisibleRect(rect);
            if (cover) {
                if (rect.width() >= playBtn.getMeasuredWidth() && rect.height() >= playBtn.getMeasuredHeight()) {
                    return !cover;
                }
            }
        }
        return true;
    }

    public void freshForwords() {
        shareTV.setText(dynamic.getForwardCounts() + "");
    }

    public void freshComment() {
        commentcountTV.setText(dynamic.getCommentCount() + "");
    }

    public void freshLike() {
        likecountTV.setSelected(dynamic.isLiked());
        likecountTV.setText(dynamic.getLikeCount() + "");
    }

    private void prepare(boolean isStart) {
        this.isStart = isStart;
        if (isPlaying) return;
        SuperPlayerModel superPlayerModel = new SuperPlayerModel();
        superPlayerModel.videoURL = dynamic.getVideoUrl();
        playerView.prepareWithMode(superPlayerModel,true);
        if (playCountListener != null && dynamic != null) {
            playCountListener.onPlay(dynamic.getVid());
        }
    }

    public void getLocalVisibleRect(Rect rect) {
        playerView.getLocalVisibleRect(rect);
    }

    @Override
    public int getHeight() {
        return playerView.getHeight();
    }

    @Override
    public void playVideo() {
        if (state > 2 || state == 0) {
            loadingIV.setVisibility(View.VISIBLE);
            playBtn.setVisibility(View.GONE);
            prepare(true);
        } else {
            if (state == 1) return;
            resumeVideo();
        }
    }

    @Override
    public void resumeVideo() {
        if (state == 2) {
            if (!isVideoCover()) {
                playerView.onResume();
            }
        }
    }
    @Override
    public void pauseVideo() {
        isStart = false;
        playerView.onPause();
    }
    @Override
    public void stopVideo() {
        isStart = false;
        playerView.stopPlay();
    }
    @Override
    public void release() {
        isStart = false;
        playerView.stopPlay();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof DynamicHolder) || this.dynamic == null) {
            return false;
        }
        DynamicHolder that = (DynamicHolder) obj;

        return this.dynamic.equals(that.dynamic);
    }

    public interface VideoClickListener {
        void onUserClick(IUser user);
        void onShare(IDynamic videoPlayer);
        void onLike(IDynamic videoPlayer, DynamicHolder videoHolder);
        void unLike(IDynamic videoPlayer, DynamicHolder videoHolder);
        void onFollow(IDynamic videoPlayer, DynamicHolder videoHolder);
        void onComment(IDynamic videoPlayer, DynamicHolder videoHolder);
    }
}
